/**
 *
 *		jsColorPallet - very basic color pallet
 *		jsColorPallet is a very basic color pallet that is bound to text fields in your document.
 *		onFocus of the selected text field the selected color pallet will apear allowing the user
 *		to select a color. There are multipul color pallets the user to select colors from.
 *
 *		Thanks to Dynarch.com for a portion of code barrowed. - Element Positioning
 *
 *		A portion Copyright 2003-2006 (c) Dynarch.com
 *		The rest Copyright 2006 (c) Skeletal Design, Inc
 *
 *		@version	v1.2 2007/04/06
 *
 */


jsColorPallet = Class.create();
jsColorPallet.prototype = {
	initialize: function(title, form, fields, bindingElement, extendedPallets) {
		/**
		 *	Initialization of jsColorPallet
		 *	Bind, Creates, and Draws out all the color pallets
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	title	string	optional	Title of the color pallet
		 *	@param	form	string	The id of the form that the color pallet will be bound to
		 *	@param	fields	array	array containing all the idz of the elements to bind the color pallet to show on
		 *	@param	bindingElement	string/object	The element to append the color pallet to
		 *	@param	extendedPallets	array	Array of custom color pallets to use with the system
		 *	@date	2007/05/19
		 */
		this.workingField = "";	// The current/last field to be evaluated to display the color pallet
		this.colorPallets = new Array();	// The array containg arrays of all the color pallets and there color
		this.attachElement = $(bindingElement); //Optional Element to bind the ColorPallet to
		this.debug = false;
		this.currentPallet = {id:1, pallet: new Array()};	// Object to manage and store each color pallet
		this.boundFields = fields;	// The array of fields to display the color pallet on

		if(extendedPallets != null)
			this.extendedPallets = extendedPallets;
		else
			this.extendedPallets = null

		this.defineColorPallets();	// Create each color pallets array
		this.drawColorPallet(title);	// Draw all the color pallets
		this.bindForm(form);	// Bind the jsColorPallet to all the forms
	},
	//Displays the Pallet reletive to the Field in question
	displayPallet: function(field, pallet){
		/**
		 *	Display the color pallets
		 *	Get the current field in focus, possitions the color pallet to that field
		 *	and then displays the color pallet.
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	field	object	An object of the current working form field
		 *	@param	pallet	integer	optional	The id of the color pallet you would like to use
		 *	@date	2006/09/15
		 */

		if(this.debug){
			console.debug(field);
			console.debug(pallet);
		}

		var show = false;
		for(i=0;i<this.boundFields.length;i++){
			if(this.boundFields[i] == field.id){
				show = true;
			}
		}

		if(!show){
			this.togglePalletDisplay('hide');
			return;
		}

		//Set the Global Ref. Var to the current working field
		if(field)
			this.workingField = field;

		var workingFieldOffset = this.workingField.scrollWidth;

		if(!pallet){
			pallet = this.currentPallet.id;
		}
		else {
			this.currentPallet.id = pallet;
		}

		if(this.debug){
			console.debug("Pallet?:");
			console.debug(pallet);
		}

		if(!this.currentPallet.pallet[pallet])
			this.currentPallet.pallet[pallet] = $('colorPallet'+ pallet);

		//Get possition of the Field in question
		var textField = this.getAbsolutePos(this.workingField);

		if(this.debug){
			console.debug(this.currentPallet);
		}

		this.currentPallet.pallet[pallet].style.top = (textField.y) + 'px';
		this.currentPallet.pallet[pallet].style.left = (textField.x + workingFieldOffset) + 'px';
		this.togglePalletDisplay('show');
	},
	togglePalletDisplay: function(what){
		/**
		 *	toggle the displaying of the color pallet
		 *	Check the current status of the color pallet and shows or hides it based on that
		 *	If what is past the color pallet will perform that function
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	what	string	optional	Force color pallet to be shown 'show' or hiden 'hide'
		 *	@date	2006/09/15
		 */

		if(this.debug){
			console.debug(what);
			console.debug(this.currentPallet);
		}

		if(what == 'show'){
			if(this.currentPallet.pallet[this.currentPallet.id].style.display == 'none'){
				this.currentPallet.pallet[this.currentPallet.id].style.display = 'block';
			}
		}
		else if(what == 'hide'){
			if(this.currentPallet.pallet[this.currentPallet.id].style.display == 'block'){
				this.currentPallet.pallet[this.currentPallet.id].style.display = 'none';
			}
		}
		else {
			if(this.currentPallet.pallet[this.currentPallet.id].style.display == 'none'){
				this.currentPallet.pallet[this.currentPallet.id].style.display = 'block';
			}
			else {
				this.currentPallet.pallet[this.currentPallet.id].style.display = 'none';
			}
		}
	},
	toggleColorPallet: function(pallet){
		/**
		 *	Changes color pallet
		 *	Switchs between each color pallet
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	pallet	integer	Id of the color pallet you want to show
		 *	@date	2006/09/15
		 */
		if(this.debug){
			console.debug("Changing to:");
			console.debug(pallet);
		}
		this.togglePalletDisplay();
		if(!this.currentPallet.pallet[pallet])
			this.currentPallet.pallet[pallet] = $('colorPallet'+ pallet);

		this.currentPallet.id = pallet;
		this.displayPallet(this.workingField);
	},
	getAbsolutePos: function(el) {
		/**
		 *	gets the position of the given element
		 *	Gets the position of the passed element. And returns that value
		 *	Function was barrowed from Dynarch.com's jsCalendar program
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	el	object	Object of the element you want to get position of
		 *	@return	r	object	returns x 'r.x', y 'r.y' of the element given
		 *	@date	2006/09/15
		 */
		  var SL = 0, ST = 0;
		  var is_div = /^div$/i.test(el.tagName);
		  if (is_div && el.scrollLeft)
			   SL = el.scrollLeft;
		  if (is_div && el.scrollTop)
			   ST = el.scrollTop;
		  var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
		  if (el.offsetParent) {
			   var tmp = this.getAbsolutePos(el.offsetParent);
			   r.x += tmp.x;
			   r.y += tmp.y;
		  }
		  return r;
	 },
	 //Return the selected color to the field in question, and hide the pallet
	 returnColor: function(anchorField){
		/**
		 *	returns the picked color
		 *	Returns ths picked color back to the currently focused element
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	anchorField	string	hex color to return back to the current field
		 *	@date	2006/09/15
		 */
		if(anchorField != '' && anchorField != null){
			this.workingField.value = anchorField;
		}
		//Hide pallet with cool effect.
		this.togglePalletDisplay();
	 },

	 defineColorPallets: function(){
		/**
		 *	Defines the color pallets
		 *	Creates each array of colors for each color pallet
		 *
		 *	Changes:
		 *	Migrated Pallets to seperate files. - 04-07-2007
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@date	2007/04/07
		 */

		this.colorPallets.push(jsColorPallet1);
		this.colorPallets.push(jsColorPallet2);

		if(this.extendedPallets != null){
			this.extendedPallets.each(
				function(iter){
					this.colorPallets.push(iter);
				}.bind(this)
			);
		}
		if(this.debug)
			console.debug(this.colorPallets);
	 },

	 drawColorPallet: function(title){
		/**
		 *	Creates each color pallet
		 *	Reads throught all the defined color pallets and draws them out
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	title	string optional	Value to initial set as the title of the color pallet
		 *	@return	var	desc
		 *	@date	2006/09/15
		 */
		 if(!title)
		 	title = "jsColorPallet";

		 var ColorPalletContainer = document.createElement('div');
		 if(this.debug)
		 	console.debug(ColorPalletContainer);

		 for(i=0;i < this.colorPallets.length;i++){
			 //Draw the begining of the Color Pallet
			if(this.colorPallets.length == (i+1)){
				var nextPallet = 0;
			}
			else{
				var nextPallet = i+1;
			}

			if(this.debug){
		 		console.debug("ColorPallet ID:");
		 		console.debug(i);
		 		console.debug(nextPallet);
			}

			var thisColorPallet = document.createElement('div');
			thisColorPallet.setAttribute('id','colorPallet'+ i +'');
			thisColorPallet.style.display = 'none';
			thisColorPallet.style.position = 'absolute';
			thisColorPallet.style.width = '202px';

			if(this.debug)
		 		console.debug(thisColorPallet);

			var colorPalletTable = document.createElement('table');
			colorPalletTable.className = 'colorPalletTable';
			colorPalletTable.cellPadding = '0';
			colorPalletTable.cellSpacing = '0';
			if(this.debug)
		 		console.debug(colorPalletTable);

			var colorPalletTablebody = document.createElement('tbody');
			if(this.debug)
		 		console.debug(colorPalletTablebody);

			var colorPalletTableRow = document.createElement('tr');
			if(this.debug)
		 		console.debug(colorPalletTableRow);

			var colorPalletTableCell = document.createElement('td');
			colorPalletTableCell.setAttribute('colSpan', this.colorPallets[i][0].length);
			//colorPalletTableCell.colSpan = '100%';
			if(this.debug)
		 		console.debug(colorPalletTableCell);

			var colorPalletHeader = document.createElement('div');
			colorPalletHeader.className = 'colorPalletHeader';
			if(this.debug)
		 		console.debug(colorPalletHeader);

			var colorPalletControlClose = document.createElement('div');
			colorPalletControlClose.className = 'colorPalletControl';
			if(this.debug)
		 		console.debug(colorPalletControlClose);

			var closeLink = document.createElement('a');
			closeLink.href = '#';
			closeLink.title = 'Close';
			closeLink.onclick = function(){this.returnColor();}.bind(this)
			if(this.debug)
		 		console.debug(closeLink);

			var closeLinkImage = document.createElement('img');
			closeLinkImage.src = 'close.gif';
			closeLinkImage.border = '0';
			if(this.debug)
		 		console.debug(closeLinkImage);

			closeLink.appendChild(closeLinkImage);
			colorPalletControlClose.appendChild(closeLink);
			colorPalletHeader.appendChild(colorPalletControlClose);
			if(this.debug)
		 		console.debug(colorPalletControlClose);

			var colorPalletControlChange = document.createElement('div');
			colorPalletControlChange.className = 'colorPalletControl';
			if(this.debug)
		 		console.debug(colorPalletControlChange);

			var changeLink = document.createElement('a');
			changeLink.href = '#';
			changeLink.title = 'Change Color Pallet';
			var changeLinkFunc = function(){this.toggleColorPallet(arguments[0]);}.bind(this, nextPallet)
			changeLink.onclick = changeLinkFunc;
			if(this.debug){
		 		console.debug("Next: "+ nextPallet);
		 		console.debug(changeLinkFunc.toSource());
		 		console.debug(changeLink);
			}

			var changeLinkImage = document.createElement('img');
			changeLinkImage.src = 'down.gif';
			changeLinkImage.border = '0';
			if(this.debug)
		 		console.debug(changeLinkImage);

			changeLink.appendChild(changeLinkImage);
			colorPalletControlChange.appendChild(changeLink);
			colorPalletHeader.appendChild(colorPalletControlChange);
			if(this.debug)
		 		console.debug(colorPalletHeader);

			var colorPalletTitle = document.createElement('div');
			colorPalletTitle.style.cssFloat = 'left';
			colorPalletTitle.setAttribute('id', 'colorPalletTitle'+ i +'');
			colorPalletTitle.innerHTML = title;
			colorPalletHeader.appendChild(colorPalletTitle);
			if(this.debug)
		 		console.debug(colorPalletHeader);

			var clearDiv = document.createElement('div');
			clearDiv.style.clear = 'both';
			if(this.debug)
		 		console.debug(clearDiv);

			colorPalletHeader.appendChild(clearDiv);
			colorPalletTableCell.appendChild(colorPalletHeader);
			colorPalletTableRow.appendChild(colorPalletTableCell);
			colorPalletTablebody.appendChild(colorPalletTableRow);
			if(this.debug)
		 		console.debug(colorPalletTablebody);

			/*colorPalletHTML += ''+
'<div id="colorPallet'+ i +'" style="display:none; position:absolute; width:202px;"><table class="colorPalletTable" cellpadding="0" cellspacing="0"><tr><td colspan="100%">'+
'<div class="colorPalletHeader">'+
'<div class="colorPalletControl"><a href="javascript:colorPallet.returnColor(\'\');" title="Close">'+
'<img src="close.gif" border="0" />'+
'</a></div>'+
'<div class="colorPalletControl"><a href="javascript:colorPallet.toggleColorPallet(\''+ (next) +'\');" title="Change Color Pallet">'+
'<img src="down.gif" border="0" />'+
'</a></div>'+
'<div style="float:left;" id="colorPalletTitle'+ i +'">' + title +'</div>'+
'<div style="clear:both;"></div></div></td></tr>';
*/

		 	//var colorPalletHTML = '';
			//Draw each row of the Color Pallet
			for(h = 0; h < this.colorPallets[i].length; h++){
					var colorRow = document.createElement('tr');

					for(c = 0; c < this.colorPallets[i][h].length; c++){
						var colorCell = document.createElement('td');
						colorCell.style.backgroundColor = this.colorPallets[i][h][c].hex;

						var colorCellLink = document.createElement('a');
						colorCellLink.onclick = function(){this.returnColor(arguments[0])}.bind(this,this.colorPallets[i][h][c].hex)
						colorCellLink.innerHTML = '&nbsp;';
						colorCellLink.className = 'colorPallet';
						colorCellLink.title = this.colorPallets[i][h][c].hex;
						colorCellLink.href = '#';

						colorCell.appendChild(colorCellLink);
						colorRow.appendChild(colorCell);

						/*var colorPalletHTML += '<td style="background-color:' + this.colorPallets[i][h][c].hex + '"><a href="javascript:colorPallet.returnColor(\'' + this.colorPallets[i][h][c].hex + '\');" title="' + this.colorPallets[i][h][c].hex + '" class="colorPallet">&nbsp;</a></td>';*/
					}
					colorPalletTablebody.appendChild(colorRow);
			}
			//Draw the end of the Color Pallet
			/*colorPalletHTML += '</table></div>';*/

			colorPalletTable.appendChild(colorPalletTablebody);
		 	thisColorPallet.appendChild(colorPalletTable);
		 	ColorPalletContainer.appendChild(thisColorPallet);
		 }
		 if (this.attachElement)
		 	this.attachElement.appendChild(ColorPalletContainer);
		 else
		 	document.body.appendChild(ColorPalletContainer);
	 },

	 changeTitle: function(title){
		/**
		 *	Changes the title of all the color pallets
		 *	Goes throught and changes all the titles on all the color pallets
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	title	string	title you would like to set the color pallet to
		 *	@date	2006/09/15
		 */
		 for(i=0;i < this.colorPallets.length; i++){
		 	$('colorPalletTitle'+ i).innerHTML = title;
		 }
	 },

	 bindForm: function(formBind){
		/**
		 *	Binds the color pallet to each form element
		 *	Goes throught the complete form and binds the color pallet to each form element
		 *
		 *	@author	NerdyNick	nick@skeletaldesign.com
		 *	@param	formBind	string	form id of the form to bind the color pallet to
		 *	@date	2006/09/15
		 */
		 var elements = $(formBind).getElements();
		 elements.each(
		 	function(iter){
		 		Event.observe(
			 		iter,
			 		'focus',
			 		function(){
			 			this.displayPallet(iter);
			 		}.bindAsEventListener(this)
			 	);
		 	}.bind(this)
		 )
	 }
}